﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PhysicalExamination5.Model.Extensions
{
    public static partial class Extensions
    {
        /// <summary>
        /// 依据属性名称及属性类型匹配，把一个实体中的数据自动复制到另一个实体中，两个实体参数必须均为可用的实例
        /// </summary>
        /// <typeparam name="S">源实体类型</typeparam>
        /// <typeparam name="D">目标实体类型</typeparam>
        /// <param name="SrcModel">源实体实例</param>
        /// <param name="DestModel">目标实体实例</param>
        public static void ModelCopy<S, D>(S SrcModel, D DestModel)
        {
            Type SrcType = SrcModel.GetType();
            PropertyInfo[] PSrcArr = SrcType.GetProperties();
            Type DestType = DestModel.GetType();
            PropertyInfo[] PDestArr = DestType.GetProperties();
            foreach (PropertyInfo SrcP in PSrcArr)
            {
                PropertyInfo DestP = DestType.GetProperty(SrcP.Name);
                if (DestP == null)
                    continue;
                if (!SrcP.PropertyType.Name.Equals(DestP.PropertyType.Name))
                    continue;
                object SrcValue = SrcP.GetValue(SrcModel, null);
                if (SrcValue != null)
                {
                    DestP.SetValue(DestModel, SrcValue, null);
                }
            }
        }
    }
}
